<!-- eslint-disable vue/html-self-closing -->
<template>
  <div v-loading="isLoading" class="page-contaniner">
    <div class="page-content">
      <div class="page-title">
        <div class="main-top flex flex-aic">
          <div class="main-title">{{ title }}</div>
          <div class="main-tips"><span class="red-tip">*</span> 为必填项</div>
        </div>
      </div>
      <!-- 基本信息 -->
      <div class="page-form-content">
        <div class="sub-form">
          <el-row :gutter="64">
            <el-form
              ref="elForm"
              :model="formData"
              :rules="rules"
              size="medium"
              label-width="110px"
            >
              <el-col :span="24">
                <el-row :gutter="0">
                  <div class="sub-title">租户信息</div>
                </el-row>
              </el-col>
              <el-col :span="12">
                <el-form-item label="租户名" prop="tenantName">
                  <el-input
                    v-model="formData.tenantName"
                    placeholder="请输入租户名"
                    maxlength="32"
                    clearable
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="租户编码" prop="">
                  <el-input
                    v-model="formData.tenantCode"
                    :disabled="true"
                    placeholder="系统自动生成"
                    maxlength="32"
                    clearable
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生效时间" prop="effectiveTm">
                  <el-date-picker
                    v-model="formData.effectiveTm"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    type="date"
                    :style="{ width: '100%' }"
                    placeholder="请选择生效时间"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="有效期至" prop="expirationTm">
                  <el-date-picker
                    v-model="formData.expirationTm"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    type="date"
                    :style="{ width: '100%' }"
                    placeholder="请选择有效期至时间"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="描述" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    type="textarea"
                    placeholder="请输入描述信息"
                    :maxlength="1000"
                    show-word-limit
                    :autosize="{ minRows: 4, maxRows: 4 }"
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-row :gutter="0">
                  <div class="sub-title">主账号信息</div>
                </el-row>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主账号" prop="userName">
                  <el-input
                    v-model="formData.userName"
                    :disabled="type === 'edit'"
                    placeholder="请输入主账号"
                    maxlength="19"
                    clearable
                    :style="{ width: '100%' }"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" prop="fullName">
                  <el-input
                    v-model="formData.fullName"
                    :disabled="type === 'detail'"
                    placeholder="请输入姓名"
                    maxlength="19"
                    clearable
                    :style="{ width: '100%' }"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <template v-if="!id">
                <el-col :span="12">
                  <el-form-item label="密码" prop="password">
                    <el-input
                      v-model="formData.password"
                      type="text"
                      class="no-autofill-pwd"
                      auto-complete="new-password"
                      placeholder="请输入密码"
                      maxlength="19"
                      clearable
                      :style="{ width: '100%' }"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input
                      v-model="formData.confirmPassword"
                      :disabled="!formData.password"
                      maxlength="19"
                      type="text"
                      class="no-autofill-pwd"
                      auto-complete="new-password"
                      placeholder="请选择确认密码"
                      :style="{ width: '100%' }"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </template>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="mobilePhone">
                  <el-input
                    v-model="formData.mobilePhone"
                    :disabled="type === 'detail'"
                    placeholder="请输入手机号码"
                    maxlength="19"
                    clearable
                    :style="{ width: '100%' }"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="formData.email"
                    :disabled="type === 'detail'"
                    maxlength="19"
                    placeholder="请输入邮箱"
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主账号角色" prop="tenantRoleId">
                  <el-select
                    v-model="formData.tenantRoleId"
                    placeholder="请选择主账号角色"
                    :style="{ width: '100%' }"
                  >
                    <el-option
                      v-for="(item, index) in infoList['mianUserRoles']"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </div>
      </div>
      <div class="page-form-footer flex flex-aic flex-jcc mt-20">
        <el-button
          v-for="(item, index) in btnList"
          :key="index"
          :type="item.type || ''"
          size="small"
          style="width: 144px"
          @click="handlerMethods(item.methods)"
        >{{ item.label }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { encryptByMd5 } from '@/utils'
import { dictMixin } from '@/mixin/dict'
import { validatePhone, emailValidate } from '@/utils/validate'
export default {
  name: 'TenantEdit',
  mixins: [dictMixin],
  data() {
    return {
      formData: {},
      rules: {
        tenantName: [
          {
            required: true,
            message: '请输入租户名',
            trigger: 'blur'
          }
        ],
        tenantCode: [
          {
            required: true,
            message: '请输入租户编码',
            trigger: 'blur'
          }
        ],
        effectiveTm: [
          {
            required: true,
            message: '请选择生效时间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            required: true,
            trigger: 'blur',
            validator: this.inputPasswordValidate
          }
        ],
        confirmPassword: [
          {
            required: true,
            message: '请确认密码',
            trigger: 'blur'
          },
          {
            required: true,
            trigger: 'blur',
            validator: this.inputPasswordConfirmValidate
          }
        ],
        expirationTm: [
          {
            required: true,
            message: '请选择有效期至时间',
            trigger: 'blur'
          }
        ],
        userName: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        tenantRoleId: [
          {
            required: true,
            message: '请选择主账号角色',
            trigger: 'change'
          }
        ],
        fullName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        mobilePhone: [
          {
            validator: (rule, value, callback) =>
              validatePhone(rule, value, callback),
            trigger: 'blur'
          }
        ],
        email: [
          {
            validator: (rule, value, callback) =>
              emailValidate(rule, value, callback),
            trigger: 'blur'
          }
        ],
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        roleCode: [
          {
            required: true,
            message: '请输入角色编码',
            trigger: 'blur'
          }
        ]
      },
      btnList: [
        {
          label: '取消',
          methods: 'cancaEdit'
        },
        {
          label: '保存并新增下一个',
          methods: 'saveFormAdd'
        },
        {
          label: '保存',
          type: 'primary',
          methods: 'saveForm'
        }
      ],
      type: 'add',
      id: '',
      roleCode: '',
      loading: false,
      isLoading: false,
      orderOptions: [],
      defaultOpen: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      defaultChecked: [],
      treeData: [],
      loadingTree: false
    }
  },
  computed: {
    /** 标题 */
    title() {
      if (this.type === 'detail') {
        return `租户详情`
      }
      return `${this.id ? '编辑' : '新增'}租户`
    }
  },
  created() {
    this.getCommonSelecteds('TenantRoleSelected', 'mianUserRoles')
    const { id } = this.$route.query
    this.$set(this, 'id', id)
    this.initFormData()
  },
  methods: {
    /** 查询详情 */
    async queryDetail(id) {
      this.isLoading = true
      try {
        const res = await this.$api.tenant.detail({ id })
        this.formData = { ...res.data }
        this.isLoading = false
      } catch (error) {
        this.isLoading = false
      }
    },
    /** 初始化 */
    initFormData() {
      this.$set(this, 'formData', {})
      this.$set(this, 'type', this.id ? 'edit' : 'add')
      if (this.id) {
        this.queryDetail(this.id)
      }
    },
    /** 事件处理 */
    handlerMethods(methods) {
      this[methods]()
    },
    /** saveForm */
    saveForm() {
      this.submitForm('save')
    },
    /** saveFormAdd */
    saveFormAdd() {
      this.submitForm('add')
    },
    /** sendForm */
    sendForm() {
      // this.submitForm('add')
    },
    /** cancaEdit */
    cancaEdit() {
      this.$store.dispatch('tabs/closeTabs', '/tenantConfig/tenantManage')
    },

    /** 保存 */
    submitForm(addType) {
      try {
        this.$refs['elForm'].validate(async (valid) => {
          if (valid) {
            // 提交表单
            this.isLoading = true
            const type = this.id ? 'update' : 'add'
            const password = encryptByMd5(this.formData.password) || ''
            const confirmPassword =
              encryptByMd5(this.formData.confirmPassword) || ''
            const res = await this.$api.tenant[type]({
              ...this.formData,
              password,
              confirmPassword
            })
            if (res.code === '1000') {
              this.$message.success(`${this.id ? '修改' : '新增'}成功`)

              if (addType === 'add') {
                this.id = ''
                this.initFormData()
              } else {
                this.cancaEdit()
              }
            }
            this.isLoading = false
          }
        })
      } catch (error) {
        this.isLoading = false
      }
    },
    /**
     * 验证密码
     */
    inputPasswordValidate(rule, value, callback) {
      //  密码正则，8到18位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符
      // const REP = new RegExp(/^.*(?=.{8, 18})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/)
      // 密码正则，8到18位，包括至少1个字母，1个数字
      const REP = new RegExp(/^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z]).*$/)
      if (!REP.test(value)) {
        callback(new Error('长度8位以上，至少包含数字和字母。'))
      } else {
        callback()
      }
    },
    /**
     * 验证确认密码
     */
    inputPasswordConfirmValidate(rule, value, callback) {
      const { password } = this.formData || {}
      //  密码正则，8到18位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符
      // const REP = new RegExp(/^.*(?=.{8, 18})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/)
      // 密码正则，8到18位，包括至少1个字母，1个数字
      const REP = new RegExp(/^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z]).*$/)
      if (!REP.test(value)) {
        callback(new Error('长度8位以上，至少包含数字和字母。'))
      } else if (password !== value) {
        callback(new Error('密码不一致'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/pageCom.scss';
.baseInfo-box {
  border: 1px solid #e7e7e7;
  padding: 0 16px;
  height: 300px;
  .row-info {
    padding: 16px 0;
    height: 100%;
    overflow-y: auto;
  }
  .info-right {
    border-left: 1px solid #e7e7e7;
    padding-left: 16px;
  }
  .info-left {
    padding-right: 16px;
  }
}

.no-autofill-pwd {
  ::v-deep .el-input__inner {
    -webkit-text-security: disc !important;
  }
}
</style>
